+function ($) {
  'use strict';
  /**
     * 对Date的扩展，将 Date 转化为指定格式的String
     * @param  string mask 默认为yyyy-MM-dd
     * @example
     * var customDate = new Date().format("yyyy-MM-dd");
     * @return string
     */
  Date.prototype.customFormat = function (mask) {
    if (mask === undefined) {
      mask = 'yyyy-MM-dd';
    }
    var d = this;
    var zeroize = function (value, length) {
      if (!length) {
        length = 2;
      }
      value = String(value);
      for (var i = 0, zeros = ''; i < length - value.length; i++) {
        zeros += '0';
      }
      return zeros + value;
    };
    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0) {
      switch ($0) {
      case 'd':
        return d.getDate();
      case 'dd':
        return zeroize(d.getDate());
      case 'ddd':
        return [
          'Sun',
          'Mon',
          'Tue',
          'Wed',
          'Thr',
          'Fri',
          'Sat'
        ][d.getDay()];
      case 'dddd':
        return [
          'Sunday',
          'Monday',
          'Tuesday',
          'Wednesday',
          'Thursday',
          'Friday',
          'Saturday'
        ][d.getDay()];
      case 'M':
        return d.getMonth() + 1;
      case 'MM':
        return zeroize(d.getMonth() + 1);
      case 'MMM':
        return [
          'Jan',
          'Feb',
          'Mar',
          'Apr',
          'May',
          'Jun',
          'Jul',
          'Aug',
          'Sep',
          'Oct',
          'Nov',
          'Dec'
        ][d.getMonth()];
      case 'MMMM':
        return [
          'January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December'
        ][d.getMonth()];
      case 'yy':
        return String(d.getFullYear()).substr(2);
      case 'yyyy':
        return d.getFullYear();
      case 'h':
        return d.getHours() % 12 || 12;
      case 'hh':
        return zeroize(d.getHours() % 12 || 12);
      case 'H':
        return d.getHours();
      case 'HH':
        return zeroize(d.getHours());
      case 'm':
        return d.getMinutes();
      case 'mm':
        return zeroize(d.getMinutes());
      case 's':
        return d.getSeconds();
      case 'ss':
        return zeroize(d.getSeconds());
      case 'l':
        return zeroize(d.getMilliseconds(), 3);
      case 'L':
        var m = d.getMilliseconds();
        if (m > 99) {
          m = Math.round(m / 10);
        }
        return zeroize(m);
      case 'tt':
        return d.getHours() < 12 ? 'am' : 'pm';
      case 'TT':
        return d.getHours() < 12 ? 'AM' : 'PM';
      case 'Z':
        return d.toUTCString().match(/[A-Z]+$/);
      // Return quoted strings with the surrounding quotes removed
      default:
        return $0.substr(1, $0.length - 2);
      }
    });
  };
  /**
     * 获取这个月的第一天
     */
  Date.prototype.getFirstDayInMonth = function () {
    var thisDate = new Date(this.getTime());
    thisDate.setDate(1);
    return thisDate;
  };
  /**
     * 获取这个月的最后一天
     */
  Date.prototype.getLastDayInMonth = function () {
    var thisDate = new Date(this.getTime());
    var thisMonth = thisDate.getMonth();
    thisDate.setMonth(thisMonth + 1);
    thisDate.setDate(0);
    return thisDate;
  };
  /**
     * 获取下个月的第一天
     */
  Date.prototype.getFirstDayInNextMonth = function () {
    var thisDate = new Date(this.getTime());
    var thisMonth = thisDate.getMonth();
    thisDate.setMonth(thisMonth + 1);
    thisDate.setDate(1);
    return thisDate;
  };
  /**
     * 获取两个时间之间的间隔天数
     * @param  Date comparand 被比较的时间对象
     * @example
     * var diffDays = new Date().getDays(getDate('2015-12-01'));
     * @return integer
     */
  Date.prototype.getDays = function (comparand) {
    var thisTime = this.getTime();
    var comparandTime = comparand.getTime();
    return parseInt((thisTime - comparandTime) / 86400000);
  };
  /**
     * 获取两个时间之间占了几个月份
     * @param  Date comparand 被比较的时间对象
     * @example
     * var diffDays = new Date().getMonths(getDate('2016-11-29'));
     * @return integer
     */
  Date.prototype.getMonths = function (comparand) {
    var months = 0;
    var thisYear = this.getFullYear();
    var comparandYear = comparand.getFullYear();
    var thisMonth = this.getMonth();
    var comparandMonth = comparand.getMonth();
    months = (comparandYear - thisYear) * 12 + comparandMonth - thisMonth + 1;
    return months;
  };
  /**
     * 根据需要加减天数，
     * @param  integer interval 负数时是前几天,正数时是后几天
     * @example
     * var diffDays = new Date().customDays(7); 获取7天的后Date对象
     * @return Date
     */
  Date.prototype.customDays = function (interval) {
    var thisTime = this.getTime();
    return new Date(thisTime + interval * 86400000);
  };
  var DateRangePickerMobile = function (element, options) {
    this.options = options;
    this.parentDom = $(element);
    this.init();
  };
  var today = new Date();
  var defaultSpecialDays = {};
  defaultSpecialDays[today.customFormat()] = lang('today');
  DateRangePickerMobile.VERSION = '0.0.1';
  DateRangePickerMobile.DEFAULTS = {
    startDate: today.customFormat(),
    endDate: today.customDays(1).customFormat(),
    minDate: today.customFormat(),
    maxDate: today.customDays(365).customFormat(),
    dateLimit: 0,
    showWeek: true,
    singleDatePicker: false,
    // 该参数暂不支持
    disabledDays: [],
    locale: {
      specialDays: defaultSpecialDays,
      startDateLabel: lang('start'),
      endDateLabel: lang('end'),
      monthAndYearText: 'M Y'+lang('year'),
      daysOfWeek: [
        lang('SUN'),
        lang('MON'),
        lang('TUE'),
        lang('WED'),
        lang('THU'),
        lang('FRI'),
        lang('SAT')
      ],
      
      monthNames: [
        lang('January'),
        lang('February'),
        lang('March'),
        lang('April'),
        lang('May'),
        lang('June'),
        lang('July'),
        lang('August'),
        lang('September'),
        lang('October'),
        lang('November'),
        lang('December')
      ]
    }
  };
  DateRangePickerMobile.EVENTS = {
    parentEvents: '.amos.drpm',
    click: 'click.amos.drpm',
    startDate: 'start.amos.drpm',
    endDate: 'end.amos.drpm'
  };
  DateRangePickerMobile.CLASS = {
    container: 'date-range-container',
    calendar: 'date-range-calendar',
    title: 'date-range-calendar-title',
    week: 'date-range-calendar-week',
    day: 'date-range-calendar-day',
    dayOption: 'date-range-calendar-option',
    dayContent: 'date-range-calender-day-content',
    dayEmpty: 'date-range-calendar-empty',
    dayDisabled: 'date-range-calendar-disabled',
    daySpecial: 'date-range-special-day',
    startDate: 'date-range-calendar-startdate',
    endDate: 'date-range-calendar-enddate',
    selectInfo: 'date-range-selected-info',
    selectTip: 'date-range-selected-tip',
    hidden: 'hidden'
  };
  DateRangePickerMobile.prototype = {
    constructor: DateRangePickerMobile,
    init: function () {
      // 获取标准化参数
      this.minDate = getDate(this.options.minDate);
      this.maxDate = getDate(this.options.maxDate);
      this.startDate = getDate(this.options.startDate);
      this.endDate = getDate(this.options.endDate);
      this.dateLimit = parseInt(this.options.dateLimit);
      this.isWeekShow = this.options.showWeek ? true : false;
      this.isSingle = this.options.singleDatePicker ? true : false;
      this.locale = this.options.locale;
      this.isStartDate = true;
      this.specialDays = this.options.locale.specialDays;
      // 创建calendars container
      this.parentDom.html('<div class="' + DateRangePickerMobile.CLASS.container + '"></div>');
      this.container = this.parentDom.find('.' + DateRangePickerMobile.CLASS.container);
      // 设置minDate前的，不会变化，所以一次设置
      var daysInFirstMonth = this.minDate.getDate();
      for (var i = 1; i < daysInFirstMonth; i++) {
        this.options.disabledDays.push(this.minDate.customDays(-i).customFormat());
      }
      // 重绘container内容
      this.renderContainer();
    },
    renderContainer: function () {
      // 去除旧的事件
      this.off();
      this.disabledDays = [];
      for (var index in this.options.disabledDays) {
        this.disabledDays.push(this.options.disabledDays[index]);
      }
      var daysInLastMonth = this.maxDate.getDate();
      var lastDayInLastMonth = this.maxDate.getLastDayInMonth().getDate();
      for (var i = lastDayInLastMonth; i > daysInLastMonth; i--) {
        this.disabledDays.push(this.maxDate.customDays(i - daysInLastMonth).customFormat());
      }
      this.container.html('');
      // 计算需要绘制的calendars
      var months = this.minDate.getMonths(this.maxDate);
      var firstDay = this.minDate.getFirstDayInMonth();
      for (i = 0; i < months; i++) {
        // 绘制calendars
        this.renderCalendar(firstDay);
        firstDay = firstDay.getFirstDayInNextMonth();
      }
      this.container.on(DateRangePickerMobile.EVENTS.click, 'td.' + DateRangePickerMobile.CLASS.dayOption, $.proxy(this.clickDate, this));
    },
    renderCalendar: function (firstDay) {
      var html = '<table class="' + DateRangePickerMobile.CLASS.calendar + '">';
      var thisMonth = firstDay.getMonth();
      var thisYear = firstDay.getFullYear();
      var monthName = this.locale.monthNames[thisMonth];
      var calendarTitle = this.locale.monthAndYearText.replace('M', monthName).replace('Y', thisYear);
      html += '<tr class="' + DateRangePickerMobile.CLASS.title + '"><td colspan="7">' + calendarTitle + '</td></tr>';
      if (this.isWeekShow) {
        html += '<tr class="' + DateRangePickerMobile.CLASS.week + '"><td>' + this.locale.daysOfWeek[0] + '</td><td>' + this.locale.daysOfWeek[1] + '</td><td>' + this.locale.daysOfWeek[2] + '</td><td>' + this.locale.daysOfWeek[3] + '</td><td>' + this.locale.daysOfWeek[4] + '</td><td>' + this.locale.daysOfWeek[5] + '</td><td>' + this.locale.daysOfWeek[6] + '</td></tr>';
      }
      // 计算需要绘制的天数，以及第一天的起始位置，从周日开始
      var lastDay = firstDay.getLastDayInMonth();
      var daysInMonth = lastDay.getDate();
      var daysBeforeFirst = firstDay.getDay();
      var daysAfterLast = 42 - daysBeforeFirst - daysInMonth;
      if (daysAfterLast >= 7) {
        daysAfterLast -= 7;
      }
      var renderCount = 0;
      html += '<tr class="' + DateRangePickerMobile.CLASS.day + '">';
      // 绘制1号前空的html
      for (var i = 0; i < daysBeforeFirst; i++, renderCount++) {
        html += '<td class="' + DateRangePickerMobile.CLASS.dayEmpty + '"></td>';
      }
      var startDateFormat = '', endDateFormat = '';
      if (typeof this.startDate === 'object' && this.startDate instanceof Date) {
        startDateFormat = this.startDate === '' ? '' : this.startDate.customFormat();
      }
      if (typeof this.endDate === 'object' && this.endDate instanceof Date) {
        endDateFormat = this.endDate === '' ? '' : this.endDate.customFormat();
      }
      // 绘制日期的html
      for (i = 1; i <= daysInMonth; i++, renderCount++) {
        if (renderCount % 7 === 0) {
          html += '</tr><tr class="' + DateRangePickerMobile.CLASS.day + '">';
        }
        var dayInLoop = firstDay.customDays(i - 1).customFormat();
        // 特殊标签
        var text = this.specialDays[dayInLoop] === undefined ? i : this.specialDays[dayInLoop];
        // 如果是开始日期
        if (startDateFormat === dayInLoop) {
          html += '<td class="' + DateRangePickerMobile.CLASS.startDate + ' ' + DateRangePickerMobile.CLASS.dayOption + '" data-value="' + dayInLoop + '"><div class="' + DateRangePickerMobile.CLASS.dayContent + '"><div class="' + DateRangePickerMobile.CLASS.selectInfo + '">' + text + '</div><div class="' + DateRangePickerMobile.CLASS.selectTip + '">' + this.locale.startDateLabel + '</div></div></td>';
        } else {
          // 如果是结束日期
          if (endDateFormat === dayInLoop) {
            html += '<td class="' + DateRangePickerMobile.CLASS.endDate + ' ' + DateRangePickerMobile.CLASS.dayOption + '" data-value="' + dayInLoop + '"><div class="' + DateRangePickerMobile.CLASS.dayContent + '"><div class="' + DateRangePickerMobile.CLASS.selectInfo + '">' + text + '</div><div class="' + DateRangePickerMobile.CLASS.selectTip + '">' + this.locale.endDateLabel + '</div></div></td>';
          } else {
            // 如果是禁用日期
            if ($.inArray(dayInLoop, this.disabledDays) !== -1) {
              html += '<td class="' + DateRangePickerMobile.CLASS.dayDisabled + '"><div class="' + DateRangePickerMobile.CLASS.dayContent + '">' + text + '</div></td>';
            } else {
              html += '<td class="' + DateRangePickerMobile.CLASS.dayOption + '" data-value="' + dayInLoop + '"><div class="' + DateRangePickerMobile.CLASS.dayContent + '">' + text + '</div></td>';
            }
          }
        }
      }
      // 绘制本月最后一天后的html
      for (i = 0; i < daysAfterLast; i++, renderCount++) {
        if (renderCount % 7 === 0) {
          html += '</tr><tr class="' + DateRangePickerMobile.CLASS.day + '">';
        }
        html += '<td class="' + DateRangePickerMobile.CLASS.dayEmpty + '"></td>';
      }
      html += '</tr></table>';
      this.container.append(html);
    },
    startDateSelected: function (triggerDate) {
      this.startDate = triggerDate;
      this.endDate = '';
      if (this.dateLimit > 0) {
        // 不能超过初始化配置的maxDate，所以需要计算maxDate进行限制
        var days = getDate(this.options.maxDate).getDays(this.startDate);
        // 如果选择的开始时间与结束时间限制差很远，则将设置小，否则初始化配置的maxDate应该不变
        if (this.dateLimit < days) {
          this.maxDate = this.startDate.customDays(this.dateLimit);
        }
      }
      this.isStartDate = false;
    },
    clickDate: function (e) {
      e.preventDefault();
      var _relatedTarget = e.currentTarget;
      var trigger = $(_relatedTarget);
      var triggerDateFormat = trigger.data('value');
      var triggerDate = getDate(triggerDateFormat);
      if (this.isStartDate) {
        this.startDateSelected(triggerDate);
      } else {
        var lastStartTime = this.startDate.getTime();
        var currentTriggerTime = triggerDate.getTime();
        if (lastStartTime > currentTriggerTime) {
          this.startDateSelected(triggerDate);
        } else {
          if (lastStartTime === currentTriggerTime) {
              if(this.startDate.customFormat() == new Date().customFormat()){
                this.endDate = triggerDate;
              }else{
                this.startDate = '';
                this.endDate = '';
                this.minDate = getDate(this.options.minDate);
                this.maxDate = getDate(this.options.maxDate);
              }
          } else {
            this.endDate = triggerDate;
          }
          this.isStartDate = true;
        }
      }      
      this.renderContainer();
      var hasStartDate = typeof this.startDate === 'object' && this.startDate instanceof Date;
      var hasEndDate = typeof this.endDate === 'object' && this.endDate instanceof Date;
      if (hasStartDate && hasEndDate) {
        var mineEvent = $.Event(DateRangePickerMobile.EVENTS.endDate, {
          relatedTarget: _relatedTarget,
          startDate: this.startDate.customFormat(),
          endDate: this.endDate.customFormat()
        });
        this.parentDom.trigger(mineEvent);
      } else {
        if (hasStartDate) {
          var mineEvent = $.Event(DateRangePickerMobile.EVENTS.startDate, {
            relatedTarget: _relatedTarget,
            startDate: this.startDate.customFormat()
          });
          this.parentDom.trigger(mineEvent);
        }
      }
    },
    off: function (e) {
      this.container.off(DateRangePickerMobile.EVENTS.parentEvents);
    }
  };
  // DateRangePickerMobile PLUGIN DEFINITION
  // =======================
  function Plugin(option, _relatedTarget) {
    return this.each(function () {
      var $this = $(this);
      var data = $this.data('amos.daterangepickermobile');
      var options = $.extend({}, DateRangePickerMobile.DEFAULTS, $this.data(), typeof option === 'object' && option);
      options.locale = $.extend({}, DateRangePickerMobile.DEFAULTS.locale, typeof option.locale === 'object' && option.locale);
      if (!data) {
        $this.data('amos.daterangepickermobile', data = new DateRangePickerMobile(this, options));
      }
      if (typeof option === 'string') {
        data[option](_relatedTarget);
      }
    });
  }
  var old = $.fn.dateRangePickerMobile;
  $.fn.dateRangePickerMobile = Plugin;
  $.fn.dateRangePickerMobile.Constructor = DateRangePickerMobile;
  // DateRangePickerMobile NO CONFLICT
  // =================
  $.fn.dateRangePickerMobile.noConflict = function () {
    $.fn.dateRangePickerMobile = old;
    return this;
  };
  /**
     * 根据传入字符串获取日期对象
     * @param  string input 暂只支持yyyy-MM-dd，2007-04-19格式
     * @return Date
     */
  var getDate = function (input) {
    if (input === '') {
      return new Date();
    }
    var splitsDate = input.split('-');
    return new Date(splitsDate[1] + '/' + splitsDate[2] + '/' + splitsDate[0]);
  };
}(jQuery);